#ifndef LOGIN_H
#define LOGIN_H

#include <memory>
#include <string>

#include "SCGI.h"
#include "Util.h"

class ALogin
	: public scgi::Application
	, public std::enable_shared_from_this<ALogin>
{
public:
	typedef std::shared_ptr<ALogin> pointer;

private:
	std::string buffer;

public:
	virtual void start() { }

	virtual void push(char * first_, char * last_)
	{
		scgi::URLDecoder decode;
		buffer.append(decode(first_, last_));
	}

	virtual void eos()
	{
		std::string & file = request->path.file;

		if(file == "login.new") on_new();
		else if(file == "login.create") on_create();
		else if(file == "login.login") on_login();
		else if(file == "login.logout") on_logout();
	}

	void on_new()
	{
		std::string mail;
		std::string password;

		scgi::Tokenizer<'=', '&'> tokenize;
		tokenize(
			buffer.begin()
			, buffer.end()
			, [&](std::string key_, std::string value_)
			{
				if(key_ == "mail") mail = value_;
				else if(key_ == "password") password = value_;
			});
		
		//mail;
	}

	void on_create()
	{

		;/*

		scgi::Session::pointer session = get_session();

		if(!session)
			session = create_session(now() + scgi::Time::seconds(60));

		request->cookie.set("sid", session->get_sid_string());
		request->cookie.path = "/";
		request->cookie.expires = session->expires;
		request->cookie.secure = false;
		*/
		buffer =
			"Status: 200 OK\r\n";
		buffer += request->cookie.to_string();
		buffer +=
			"Content-type: text/plain\r\n"
			"\r\n";
		
		write(buffer, this, &ALogin::finish);

		//set_session(session);
	}

	void on_login() { }

	void on_logout() { }

	void finish() { close_socket(); }
};

class FLogin : public scgi::Factory
{
public:
	typedef std::shared_ptr<FLogin> pointer;

public:
	virtual std::string name() const { return "login"; }
	virtual scgi::Application::pointer create_application()
	{
		return scgi::Application::pointer(new ALogin);
	}

	static Factory::pointer create() { return Factory::pointer(new FLogin); }
};







#endif // LOGIN_H
